import sys  
import time
import json
import os
from PyQt6.QtWidgets import (  
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton,  
    QLabel, QProgressBar, QGridLayout, QLineEdit, QDateEdit, QTableWidget,  
    QTableWidgetItem, QHeaderView, QAbstractItemView, QDialog, QMessageBox ,
    QGridLayout,
)  
from PyQt6.QtCore import Qt, QDateTime, QTime , QDate, QThread,pyqtSignal
from PyQt6.QtGui import QColor,QBrush  
  
class WorkerThread(QThread):  
    status=0
    signalRunText = pyqtSignal(str)  
    signalProgressVal = pyqtSignal(int)  
    progressVal = 0

    # 0 未执行
    signalRunStatus = pyqtSignal(int)

    def changeValues(self):
        if self.progressVal<100:
            self.progressVal+=1

        self.signalProgressVal.emit(self.progressVal)

  
    # 重写QThread的run方法，这里是线程实际执行的地方  
    def run(self): 

        while True:
            # 未启动，就休息1秒钟
            if self.status ==0:
                time.sleep(0.1)
                continue
            # 执行状态
            elif self.status==1:
                self.changeValues()
                time.sleep(0.1)
                continue
            


class MainWindow(QMainWindow):  
    labelWidth=140
    dateEditWidth=100
    dateEditFormat='yyyy-MM-dd'
    queryStatus = 0

    def __init__(self):  
        super().__init__()  
        self.initUI()  
        self.initUIEvent()
        self.loadDateEditValues()
        self.initThread1()

    def initThread1(self):
        self.workThread = WorkerThread()
        self.workThread.signalProgressVal.connect(self.updateExecProgressVal)
        self.workThread.start()
  
    def initUIEvent(self):
        self.start_query_button.clicked.connect(self.on_start_query_clicked)  
        self.copy_button.clicked.connect(self.on_copy_button_clicked)

    def initUI(self):  
        self.setWindowTitle('数据查询分析')  
        self.setGeometry(100,100,800, 600)  # 设置固定大小  
        # self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowMinMaxButtonsHint)  # 隐藏最大化和最小化按钮  
  
        # 创建中央部件  
        central_widget = QWidget(self)  
        self.setCentralWidget(central_widget)  
  
        # 创建布局 
        grid_layout = QGridLayout(central_widget) 

  
        # 第1行：数据查询分析 Label 和进度条  
        data_query_label = QLabel('数据查询分析时间段:')  
        data_query_label.setMinimumWidth(self.labelWidth)
        self.start1_date_edit = QDateEdit(self)  
        self.end1_date_edit = QDateEdit(self)  
        self.start1_date_edit.setCalendarPopup(True)  
        self.end1_date_edit.setCalendarPopup(True)  
        self.start1_date_edit.setMinimumWidth(self.dateEditWidth)
        self.end1_date_edit.setMinimumWidth(self.dateEditWidth)
        self.start1_date_edit.setDisplayFormat(self.dateEditFormat)
        self.end1_date_edit.setDisplayFormat(self.dateEditFormat)

        lblZhi2=QLabel('至')
        lblZhi2.setMaximumWidth(40)
        lblZhi2.setAlignment( Qt.AlignmentFlag.AlignCenter )

        grid_layout.addWidget(data_query_label,0,0)  
        grid_layout.addWidget(self.start1_date_edit,0,1)  
        grid_layout.addWidget(lblZhi2,0,2)  
        grid_layout.addWidget(self.end1_date_edit,0,3)  

        # 创建复制时间的按钮  
        self.copy_button = QPushButton('复制时间')  
        # 设置按钮的最大宽度（如果需要的话）  
        self.copy_button.setMaximumWidth(80)  
        grid_layout.addWidget(self.copy_button,0,4)  
        
  
        # 第2行：住院查询 Label 和进度条  
        hospital_query_label = QLabel('住院查询时间段:')  

        self.start2_date_edit = QDateEdit(self)  
        self.end2_date_edit = QDateEdit(self)  
        self.start2_date_edit.setCalendarPopup(True)  
        self.end2_date_edit.setCalendarPopup(True)  
        self.start2_date_edit.setMinimumWidth(self.dateEditWidth)
        self.end2_date_edit.setMinimumWidth(self.dateEditWidth)
        self.start2_date_edit.setDisplayFormat(self.dateEditFormat)
        self.end2_date_edit.setDisplayFormat(self.dateEditFormat)

        lblZhi3=QLabel('至')
        lblZhi3.setMaximumWidth(40)
        lblZhi3.setAlignment( Qt.AlignmentFlag.AlignCenter )

        grid_layout.addWidget(hospital_query_label,1,0)  
        grid_layout.addWidget(self.start2_date_edit,1,1)  
        grid_layout.addWidget(lblZhi3,1,2)  
        grid_layout.addWidget(self.end2_date_edit,1,3)  
  
        # 第3行：医师接诊人数 Label 和进度条  
        doctor_attendance_label = QLabel('费用发展趋势时间段:')  

        self.start3_date_edit = QDateEdit(self)  
        self.end3_date_edit = QDateEdit(self)  
        self.start3_date_edit.setCalendarPopup(True)  
        self.end3_date_edit.setCalendarPopup(True)  
        self.start3_date_edit.setMinimumWidth(self.dateEditWidth)
        self.end3_date_edit.setMinimumWidth(self.dateEditWidth)
        self.start3_date_edit.setDisplayFormat(self.dateEditFormat)
        self.end3_date_edit.setDisplayFormat(self.dateEditFormat)

        lblZhi4=QLabel('至')
        lblZhi4.setMaximumWidth(40)
        lblZhi4.setAlignment( Qt.AlignmentFlag.AlignCenter )

        grid_layout.addWidget(doctor_attendance_label,2,0)  
        grid_layout.addWidget(self.start3_date_edit,2,1)  
        grid_layout.addWidget(lblZhi4,2,2)  
        grid_layout.addWidget(self.end3_date_edit,2,3)  

        # 第4行：执行进度  
        execution_status_label = QLabel('执行进度:')  
        capturing_progress_label =QLabel('未执行')
        capturing_progress_label.setStyleSheet("QLabel { color: blue; }")
        self.exec_progress  = QProgressBar(self)  
        grid_layout.addWidget(execution_status_label,3,0)  
        grid_layout.addWidget(capturing_progress_label,3,1,1,2)  
        grid_layout.addWidget(self.exec_progress,3,4)  
  
        # 第4行：开始查询按钮  
        self.start_query_button = QPushButton('开始抓取', self)  
        
        self.start_query_button.setStyleSheet('QPushButton { background-color: blue; color: white; }')  
        grid_layout.addWidget(self.start_query_button,4,1)  
  
        # 表格组件  
        self.tblRecord = QTableWidget(self)  
        self.tblRecord.setColumnCount(6)  

        # 设置表格列宽
        self.tblRecord.setColumnWidth(0,50)
        self.tblRecord.setColumnWidth(1,160)
        self.tblRecord.setColumnWidth(5,130)

        self.tblRecord.setHorizontalHeaderLabels(['编号', '执行时间', '数据查询分析', '住院查询', '医师接诊人数', '总完成情况'])  
        self.tblRecord.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)  
        self.tblRecord.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)  
        self.tblRecord.setRowCount(0)  # 初始行数为0，后面动态添加  
        grid_layout.addWidget(self.tblRecord,5,0,1,5)  

        # 添加一些示例数据  
        for row in range(4):  # 遍历所有行  
            self.tblRecord.setRowCount(row+1)
            item1 = QTableWidgetItem(f"{row+1}") 
            self.tblRecord.setItem(row, 0, item1)  

            item2 = QTableWidgetItem(f"2024-11-23 11:23:13") 
            self.tblRecord.setItem(row, 1, item2)  
            
            item3 = QTableWidgetItem(f"22%") 
            self.tblRecord.setItem(row, 2, item3)  
            item4 = QTableWidgetItem(f"22%") 
            self.tblRecord.setItem(row, 3, item4)  
            item5 = QTableWidgetItem(f"22%") 
            self.tblRecord.setItem(row, 4, item5)  
            

            # item = QTableWidgetItem(f"R{row+1}, C{column+1}")  # 注意索引从0开始，但显示时可能需要从1开始  
            # item.setForeground( QBrush(QColor('red') ) )
            # self.tblRecord.setItem(row, column, item)  
  
        # 添加操作列按钮  
        self.add_operation_buttons()  

        self.tblRecord.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  
        self.tblRecord.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)  
        self.tblRecord.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)  
    
    # 加载DateEdit的日期值
    def loadDateEditValues(self):
        # 判断文件名是否存在
        if not os.path.exists('date_edit_values.json'):
            print('not exists date_edit_values.json')
            return

        with open('date_edit_values.json','r',encoding='utf-8') as f1:
            try:
                js1=json.load(f1)
            except:
                print('date_edit_values.json is not a json file')
                return
            
            if js1 is not None:
                if 'start1_date_edit_val' in js1:
                    self.start1_date_edit.setDate( QDate.fromString( js1['start1_date_edit_val'], self.dateEditFormat) )
                if 'end1_date_edit_val' in js1:
                    self.end1_date_edit.setDate( QDate.fromString( js1['end1_date_edit_val'], self.dateEditFormat) )
                if 'start2_date_edit_val' in js1:
                    self.start2_date_edit.setDate( QDate.fromString( js1['start2_date_edit_val'], self.dateEditFormat) )
                if 'end2_date_edit_val' in js1:
                    self.end2_date_edit.setDate( QDate.fromString( js1['end2_date_edit_val'], self.dateEditFormat) )
                if 'start3_date_edit_val' in js1:
                    self.start3_date_edit.setDate( QDate.fromString( js1['start3_date_edit_val'], self.dateEditFormat) )
                if 'end3_date_edit_val' in js1:
                    self.end3_date_edit.setDate( QDate.fromString( js1['end3_date_edit_val'], self.dateEditFormat) )

                

    # 保存DateEdit的值
    def saveDateEditValues(self):
        js1={'start1_date_edit_val':self.start1_date_edit.text(),
             'end1_date_edit_val':self.end1_date_edit.text(),
             'start2_date_edit_val':self.start2_date_edit.text(),
             'end2_date_edit_val':self.end2_date_edit.text(),
             'start3_date_edit_val':self.start3_date_edit.text(),
             'end3_date_edit_val':self.end3_date_edit.text(),
             }

        strjs1=json.dumps(js1)
        with open('date_edit_values.json','w',encoding='utf-8') as f1:
            f1.write(strjs1)


    def add_operation_buttons(self):  
        # 假设已经添加了一些行到表格中  
        for row in range(self.tblRecord.rowCount()):  
            view_button = QPushButton('查看', self)  
            view_button.setMinimumHeight(20)
            view_button.clicked.connect(lambda checked, row=row: self.on_view_clicked(row))  
            delete_button = QPushButton('删除', self)  
            delete_button.setMinimumHeight(20)
            delete_button.clicked.connect(lambda checked, row=row: self.on_delete_clicked(row))  
  
            # 创建一个水平布局来容纳查看和删除按钮  
            button_layout = QHBoxLayout()  
            button_layout.addWidget(view_button)  
            button_layout.addWidget(delete_button)  
            
  
            # 将布局添加到表格的单元格中  
            widget = QWidget()  
            widget.setLayout(button_layout)  
            self.tblRecord.setCellWidget(row, 5, widget)  # 操作列是最后一列  
  
    def on_view_clicked(self, row):  
        # 显示详情信息的对话框，这里只是简单打印行号  
        # self.start_date_edit.setDisabled(True)
        self.start_date_edit.setDate( QDate.currentDate() )
  
    def on_delete_clicked(self, row):  
        # 提示用户是否删除该记录  
        reply = QMessageBox.question(self, '删除记录', f'你确定要删除第 {row + 1} 条记录吗?',  
                                     QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                                       QMessageBox.StandardButton.No)  
  
        if reply == QMessageBox.StandardButton.Yes:  
            # 删除表格中的行  
            self.tblRecord.removeRow(row)  

    def updateWorkThread(self):
        self.workThread.status =self.queryStatus
        
    def on_copy_button_clicked(self):
        self.start2_date_edit.setDate(self.start1_date_edit.date() )
        self.start3_date_edit.setDate(self.start1_date_edit.date() )

        self.end2_date_edit.setDate(self.end1_date_edit.date() )
        self.end3_date_edit.setDate(self.end1_date_edit.date() )
         

    def on_start_query_clicked(self):  
        # 开始查询的逻辑，这里只是简单改变按钮颜色  
        if self.queryStatus==0:
            self.queryStatus=1
            self.start_query_button.setStyleSheet('QPushButton { background-color: gray; color: white; }')
            self.start_query_button.setText('取消执行')

            self.start1_date_edit.setDisabled(True)
            self.end1_date_edit.setDisabled(True)
            self.start2_date_edit.setDisabled(True)
            self.end2_date_edit.setDisabled(True)
            self.start3_date_edit.setDisabled(True)
            self.end3_date_edit.setDisabled(True)
            
            
        else:
            self.queryStatus=0
            self.start_query_button.setStyleSheet('QPushButton { background-color: blue; color: white; }')
            self.start_query_button.setText('开始抓取')

            self.start1_date_edit.setDisabled(False)
            self.end1_date_edit.setDisabled(False)
            self.start2_date_edit.setDisabled(False)
            self.end2_date_edit.setDisabled(False)
            self.start3_date_edit.setDisabled(False)
            self.end3_date_edit.setDisabled(False)
            
        self.updateWorkThread()
        self.saveDateEditValues()    


    def updateExecProgressVal(self, val):
        self.exec_progress.setValue(val) 

    def updateRunStatus(self, status):
        if status==0:
            self.start2_date_edit.setDisabled=False
            self.end2_date_edit.setDisabled=False
        else:
            self.start2_date_edit.setDisabled=True
            self.end2_date_edit.setDisabled=True   
            

  
if __name__ == '__main__':  
    app = QApplication(sys.argv)  
    ex = MainWindow()  
    ex.show()  
    sys.exit(app.exec())